package com.kt.controller;

import com.kt.dao.imp.UserDAOImp;
import com.kt.domain.User;
import com.kt.service.imp.UserServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register.do")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        UserDAOImp userDAOImp = new UserDAOImp();
        UserServiceImp userServiceImp = new UserServiceImp();
        String username = req.getParameter("username");
        if (userServiceImp.findByUsername(username) != null) {
            resp.getWriter().write("用户名已存在");
            return;
        }
        String phone = req.getParameter("phone");
        if (userServiceImp.findByPhone(phone) != null) {
            resp.getWriter().write("此手机号已被注册");
            return;
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(req.getParameter("password"));
        user.setPhone(phone);
        user.setName(req.getParameter("name"));
        user.setLevel(Integer.valueOf(req.getParameter("level")));
        System.out.println("user = " + user);
        if (userDAOImp.addUser(user) == 0) {
            resp.getWriter().write("error");
            return;
        }
        resp.getWriter().write("ok");


    }
}
